package com.qiguliuxing.dts.job.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.common.collect.Maps;
import com.qiguliuxing.dts.common.constant.CommConsts;
import com.qiguliuxing.dts.db.bean.DtsUserSeckillSubInfo;
import com.qiguliuxing.dts.db.domain.DtsSeckillBatch;
import com.qiguliuxing.dts.service.base.DtsUserSeckillSubService;
import com.qiguliuxing.dts.service.notify.SecondSeckillNotifyService;
import com.qiguliuxing.dts.service.seckill.WxSeckillService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 秒杀消息通知job
 *
 * @author 1197673878@qq.com
 * @since 2020年9月9日 上午11:47:50
 */
@Component
public class SeckillSubMsgJob implements SimpleJob {
    private static final Logger logger = getLogger(SeckillSubMsgJob.class);

    @Autowired
    private DtsUserSeckillSubService dtsUserSeckillSubService;

    @Autowired
    private SecondSeckillNotifyService secondSeckillNotifyService;

    @Autowired
    private WxSeckillService wxSeckillService;


    /**
     * 执行作业.
     *
     * @param shardingContext 分片上下文
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info(String.format("Thread ID: %s, 作业分片总数: %s, " +
                        "当前分片项: %s.当前参数: %s," +
                        "作业名称: %s.作业自定义参数: %s",
                Thread.currentThread().getId(),
                shardingContext.getShardingTotalCount(),
                shardingContext.getShardingItem(),
                shardingContext.getShardingParameter(),
                shardingContext.getJobName(),
                shardingContext.getJobParameter()
        ));

        Map<String, Object> paramsMap = Maps.newHashMapWithExpectedSize(CommConsts.INIT_HASH_MAP_SIZE);
        paramsMap.put("shardingTotalCount", shardingContext.getShardingTotalCount());
        paramsMap.put("shardingItem", shardingContext.getShardingItem());

        /**未开始的秒杀批次**/
        DtsSeckillBatch timeBatchConfig = this.getTimeBatchConfig();

        if(Objects.isNull(timeBatchConfig)){
            return;
        }
        //查询需要被通知的人
        List<DtsUserSeckillSubInfo> noticeUserList = dtsUserSeckillSubService.selectNotifyUser(paramsMap);

        secondSeckillNotifyService.notifyUserSeckill(timeBatchConfig, noticeUserList);
    }

    private DtsSeckillBatch getTimeBatchConfig(){
        List<DtsSeckillBatch> list = wxSeckillService.getTimeBatchConfigs();
        if (CollectionUtils.isNotEmpty(list)) {
            //升序排列
            List<DtsSeckillBatch> sortTimeList = list.stream().sorted(Comparator.comparing(DtsSeckillBatch::getSort)).collect(Collectors.toList());

            List<DtsSeckillBatch> curBatchConfigs = sortTimeList.stream().filter(e -> wxSeckillService.inBatchTime(e)).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(curBatchConfigs)){
                return null;
            }
            DtsSeckillBatch curBatchConfig = curBatchConfigs.get(0);
            //计算出当前进行中的下一个秒杀时间段
            DtsSeckillBatch tempConfig;
            int nextIndex = 0;
            for (int i = 0; i < sortTimeList.size(); i++) {
                tempConfig = sortTimeList.get(i);
                if(tempConfig.getId().intValue() == curBatchConfig.getId().intValue()){
                    nextIndex = i+1;
                    break;
                }
            }
            if(sortTimeList.size() == nextIndex){
                //今日秒杀进行完毕
                return null;
            }
            return sortTimeList.get(nextIndex);
        }
        return null;
    }
}
